package com.wutongyu.mannyburger;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.card.MaterialCardView;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";
    private ViewPager2 bannerViewPager;
    private RecyclerView popularItemsRecyclerView;
    private RecyclerView categoriesRecyclerView;
    private Handler bannerHandler;
    private Runnable bannerRunnable;
    
    // 假设的数据列表
    private List<BannerItem> bannerList;
    private List<Product> popularProducts;
    private List<Category> categories;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 使用新的首页布局
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化控件
        bannerViewPager = view.findViewById(R.id.banner_viewpager);
        popularItemsRecyclerView = view.findViewById(R.id.popular_items_recyclerview);
        categoriesRecyclerView = view.findViewById(R.id.categories_recyclerview);
        
        // 初始化数据
        setupData();
        
        // 设置轮播图
        setupBanner();
        
        // 设置热门商品列表
        setupPopularItems();
        
        // 设置分类列表
        setupCategories();
        
        // 设置点击事件
        view.findViewById(R.id.all_menu_card).setOnClickListener(v -> 
            navigateToOrderFragment());
    }

    private void setupData() {
        // 热门商品数据
        popularProducts = new ArrayList<>();
        popularProducts.add(new Product(1, "经典牛肉汉堡", 20.0, "美味多汁的经典牛肉汉堡", "汉堡", R.drawable.burger_cheese));
        popularProducts.add(new Product(2, "芝士培根汉堡", 25.0, "香浓芝士与培根的完美搭配", "汉堡", R.drawable.burger_classic));
        popularProducts.add(new Product(3, "鸡肉汉堡", 18.0, "鲜嫩多汁的鸡肉汉堡", "汉堡", R.drawable.burger_chicken));
        popularProducts.add(new Product(4, "墨西哥风味汉堡", 23.0, "墨西哥风味的美味汉堡", "汉堡", R.drawable.burger_mexican));
        
        // 轮播图数据 - 现在每个轮播图项目都与特定产品关联
        bannerList = new ArrayList<>();
        bannerList.add(new BannerItem(R.drawable.meal_double, 15)); // 超值双人餐
        bannerList.add(new BannerItem(R.drawable.meal_classic, 13)); // 经典汉堡套餐
        bannerList.add(new BannerItem(R.drawable.meal_cheese, 14)); // 芝士堡全家桶
        bannerList.add(new BannerItem(R.drawable.snack_nuggets, 9)); // 鸡米花
        bannerList.add(new BannerItem(R.drawable.burger_chicken, 3)); // 鸡肉汉堡
        
        // 分类数据
        categories = new ArrayList<>();
        categories.add(new Category(1, "汉堡", R.drawable.burger_chicken));
        categories.add(new Category(2, "小吃", R.drawable.snack_fries));
        categories.add(new Category(3, "饮料", R.drawable.drink_juice));
        categories.add(new Category(4, "甜点", R.drawable.snack_onion_rings));
        categories.add(new Category(5, "套餐", R.drawable.meal_cheese));
    }

    private void setupBanner() {
        BannerAdapter bannerAdapter = new BannerAdapter(bannerList);
        bannerViewPager.setAdapter(bannerAdapter);
        
        // 设置无限循环滚动
        bannerViewPager.setOffscreenPageLimit(1);
        bannerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                resetBannerLooper();
            }
        });
        
        // 自动轮播
        startBannerLoop();
    }
    
    private void startBannerLoop() {
        bannerHandler = new Handler();
        bannerRunnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = bannerViewPager.getCurrentItem();
                if (currentItem == bannerList.size() - 1) {
                    bannerViewPager.setCurrentItem(0, true);
                } else {
                    bannerViewPager.setCurrentItem(currentItem + 1, true);
                }
                bannerHandler.postDelayed(this, 3000);
            }
        };
        bannerHandler.postDelayed(bannerRunnable, 3000);
    }

    private void resetBannerLooper() {
        if (bannerHandler != null && bannerRunnable != null) {
            bannerHandler.removeCallbacks(bannerRunnable);
            bannerHandler.postDelayed(bannerRunnable, 3000);
        }
    }

    private void setupPopularItems() {
        PopularItemAdapter popularItemAdapter = new PopularItemAdapter(popularProducts);
        popularItemsRecyclerView.setAdapter(popularItemAdapter);
        
        // 使用自定义布局管理器，设置额外边距
        LinearLayoutManager layoutManager = new LinearLayoutManager(
                requireContext(), LinearLayoutManager.HORIZONTAL, false);
        popularItemsRecyclerView.setLayoutManager(layoutManager);
        
        // 添加间距装饰器
        popularItemsRecyclerView.addItemDecoration(new ItemSpacingDecoration(8));
        
        popularItemAdapter.setOnItemClickListener(position -> {
            // 点击热门商品项，跳转到商品详情页
            Product product = popularProducts.get(position);
            Intent intent = new Intent(requireContext(), ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            startActivity(intent);
        });
    }

    private void setupCategories() {
        CategoryAdapter categoryAdapter = new CategoryAdapter(categories);
        categoriesRecyclerView.setAdapter(categoryAdapter);
        
        // 使用自定义布局管理器，设置额外边距
        LinearLayoutManager layoutManager = new LinearLayoutManager(
                requireContext(), LinearLayoutManager.HORIZONTAL, false);
        categoriesRecyclerView.setLayoutManager(layoutManager);
        
        // 添加间距装饰器
        categoriesRecyclerView.addItemDecoration(new ItemSpacingDecoration(8));
        
        categoryAdapter.setOnItemClickListener(position -> {
            // 点击分类项，导航到点单页并过滤该分类
            navigateToOrderFragment();
        });
    }
    
    private void navigateToOrderFragment() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).navigateToTab(R.id.navigation_order);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 暂停轮播
        if (bannerHandler != null && bannerRunnable != null) {
            bannerHandler.removeCallbacks(bannerRunnable);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 恢复轮播
        if (bannerHandler != null && bannerRunnable != null) {
            bannerHandler.postDelayed(bannerRunnable, 3000);
        }
    }

    // 轮播图项目类，用于关联轮播图与产品
    public static class BannerItem {
        private int imageResId; // 轮播图图片资源ID
        private int productId;  // 关联的产品ID

        public BannerItem(int imageResId, int productId) {
            this.imageResId = imageResId;
            this.productId = productId;
        }

        public int getImageResId() {
            return imageResId;
        }

        public int getProductId() {
            return productId;
        }
    }

    // Banner适配器
    private class BannerAdapter extends RecyclerView.Adapter<BannerAdapter.BannerViewHolder> {
        private List<BannerItem> bannerList;

        public BannerAdapter(List<BannerItem> bannerList) {
            this.bannerList = bannerList;
        }

        @NonNull
        @Override
        public BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_banner, parent, false);
            return new BannerViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull BannerViewHolder holder, int position) {
            BannerItem bannerItem = bannerList.get(position);
            holder.bannerImageView.setImageResource(bannerItem.getImageResId());
            
            holder.itemView.setOnClickListener(v -> {
                // 直接使用关联的产品ID跳转到详情页
                Intent intent = new Intent(requireContext(), ProductDetailActivity.class);
                intent.putExtra("product_id", bannerItem.getProductId());
                startActivity(intent);
            });
        }

        @Override
        public int getItemCount() {
            return bannerList.size();
        }

        class BannerViewHolder extends RecyclerView.ViewHolder {
            ImageView bannerImageView;

            public BannerViewHolder(@NonNull View itemView) {
                super(itemView);
                bannerImageView = itemView.findViewById(R.id.banner_image);
            }
        }
    }

    // PopularItem适配器
    private class PopularItemAdapter extends RecyclerView.Adapter<PopularItemAdapter.PopularItemViewHolder> {
        private List<Product> productList;
        private OnItemClickListener listener;

        public PopularItemAdapter(List<Product> productList) {
            this.productList = productList;
        }

        @NonNull
        @Override
        public PopularItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_popular, parent, false);
            return new PopularItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull PopularItemViewHolder holder, int position) {
            Product product = productList.get(position);
            holder.productNameTextView.setText(product.getName());
            holder.productPriceTextView.setText("¥" + product.getPrice());
            
            // 添加图片设置代码
            if (product.getImageResId() != 0) {
                holder.productImageView.setImageResource(product.getImageResId());
            } else {
                // 设置默认图片
                holder.productImageView.setImageResource(R.drawable.bg);
            }
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onItemClick(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return productList.size();
        }

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.listener = listener;
        }

        class PopularItemViewHolder extends RecyclerView.ViewHolder {
            TextView productNameTextView;
            TextView productPriceTextView;
            ImageView productImageView;

            public PopularItemViewHolder(@NonNull View itemView) {
                super(itemView);
                productNameTextView = itemView.findViewById(R.id.product_name);
                productPriceTextView = itemView.findViewById(R.id.product_price);
                productImageView = itemView.findViewById(R.id.product_image);
            }
        }
    }

    // Category适配器
    private class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder> {
        private List<Category> categoryList;
        private OnItemClickListener listener;

        public CategoryAdapter(List<Category> categoryList) {
            this.categoryList = categoryList;
        }

        @NonNull
        @Override
        public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_category, parent, false);
            return new CategoryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
            Category category = categoryList.get(position);
            holder.categoryNameTextView.setText(category.getName());
            holder.categoryImageView.setImageResource(category.getImageResId());
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onItemClick(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return categoryList.size();
        }

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.listener = listener;
        }

        class CategoryViewHolder extends RecyclerView.ViewHolder {
            TextView categoryNameTextView;
            ImageView categoryImageView;

            public CategoryViewHolder(@NonNull View itemView) {
                super(itemView);
                categoryNameTextView = itemView.findViewById(R.id.category_name);
                categoryImageView = itemView.findViewById(R.id.category_image);
            }
        }
    }

    // 点击监听器接口
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    // 分类数据类
    public static class Category {
        private int id;
        private String name;
        private int imageResId;

        public Category(int id, String name, int imageResId) {
            this.id = id;
            this.name = name;
            this.imageResId = imageResId;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getImageResId() {
            return imageResId;
        }
    }

    // 自定义间距装饰器
    private class ItemSpacingDecoration extends RecyclerView.ItemDecoration {
        private int spacing;

        public ItemSpacingDecoration(int spacing) {
            this.spacing = spacing;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, 
                                   @NonNull RecyclerView parent, 
                                   @NonNull RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            if (position != RecyclerView.NO_POSITION) {
                outRect.left = spacing;
                outRect.right = spacing;
            }
        }
    }
} 